package com.example.mqttdemo.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mqttdemo.entity.pojo.SensorData;
import com.example.mqttdemo.service.DeviceCommandsService;
import com.example.mqttdemo.service.SensorDataService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttMessageListener implements IMqttMessageListener {
    @Autowired
    private SensorDataService sensorDataService;
    
    @Autowired
    private DeviceCommandsService deviceCommandsService;

    @Override
    public void messageArrived(String topic, MqttMessage message){
        if (message == null || message.getPayload() == null) {
            log.warn("接收到空的MQTT消息");
            return;
        }
        String payload = new String(message.getPayload());
        if (payload.trim().isEmpty()) {
            log.warn("接收到空的MQTT消息负载");
            return;
        }
        try {
            JSONObject jsonObject = JSON.parseObject(payload);
            if (jsonObject == null) {
                log.warn("无法解析MQTT消息为JSON格式: {}", payload);
                return;
            }

            // 判断消息类型：设备响应消息 或 传感器数据
            if (jsonObject.containsKey("messageType") && "response".equals(jsonObject.getString("messageType"))) {
                // 处理设备响应消息
                handleDeviceResponse(jsonObject);
            } else if (jsonObject.containsKey("temperature") && jsonObject.containsKey("humidity")) {
                // 处理传感器数据
                handleSensorData(jsonObject);
            } else {
                log.warn("未知的MQTT消息类型: {}", payload);
            }

        } catch (Exception e) {
            log.error("处理MQTT消息时发生错误: {}", e.getMessage(), e);
        }
    }

    /**
     * 处理设备响应消息
     */
    private void handleDeviceResponse(JSONObject jsonObject) {
        if (!jsonObject.containsKey("deviceId")) {
            log.warn("设备响应消息缺少deviceId字段: {}", jsonObject.toJSONString());
            return;
        }
        
        String deviceId = jsonObject.getString("deviceId");
        deviceCommandsService.updateResponseData(deviceId, jsonObject);
        log.info("处理设备响应成功: deviceId={}", deviceId);
    }

    /**
     * 处理传感器数据
     */
    private void handleSensorData(JSONObject jsonObject) {
        // 验证必要字段
        if (!jsonObject.containsKey("deviceId") ||
                !jsonObject.containsKey("temperature") ||
                !jsonObject.containsKey("humidity")) {
            log.warn("传感器数据消息缺少必要字段: {}", jsonObject.toJSONString());
            return;
        }

        SensorData data = new SensorData();
        data.setDeviceId(jsonObject.getString("deviceId"));

        try {
            data.setTemperature(jsonObject.getBigDecimal("temperature"));
            data.setHumidity(jsonObject.getBigDecimal("humidity"));
        } catch (Exception parseException) {
            log.warn("解析传感器数据失败,temperature或humidity格式错误: {}", jsonObject.toJSONString());
            return;
        }

        sensorDataService.save(data);
        log.info("保存传感器数据成功: deviceId={}", data.getDeviceId());
    }
}
